package com.sensorfriendly.ui;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sensorfriendly.AppConstants;
import com.sensorfriendly.R;
import com.sensorfriendly.util.CallUtil;
/**
 * 
 * Main dashboard contains Gallery and Scenarios.
 * Deprecated per Jeannie's suggestion.
 *
 */
public class MainActivity extends Activity implements OnClickListener{	
	public static final int GALLERY_ID =0;
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LinearLayout aButton = (LinearLayout) (findViewById(R.id.gallery));
        LinearLayout gButton = (LinearLayout) (findViewById(R.id.scenario));
        
        aButton.setOnClickListener(this);
        gButton.setOnClickListener(this);
        
        ((TextView)findViewById(R.id.page_title)).setText("Home");
        ((ImageView)findViewById(R.id.ab_settings)).setOnClickListener(this);
    }
    
	@Override
	public void onClick(View v) {
		switch(v.getId()){

		case R.id.scenario:
			//Toast.makeText(this, "Nothing implemented for this", Toast.LENGTH_LONG).show();
			Intent intent = new Intent(this, DashboardNavigationActivity.class);
			startActivity(intent);
    		break;
		case R.id.gallery:
			Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
	        photoPickerIntent.setType("image/*");
	        startActivityForResult(photoPickerIntent, GALLERY_ID);
			break;
		case R.id.footer_button:
			String phoneNum = PreferenceManager.getDefaultSharedPreferences(this).getString(AppConstants.PREFERENCE_EMERGENCY_NUMBER, "");
			if(phoneNum.length()>1){
				CallUtil.call(this, phoneNum);
			}
			break;
		
		case R.id.ab_settings:
			Intent settingsIntent = new Intent(this, SettingsActivity.class);
			startActivity(settingsIntent);
			try {
				backupDb();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		}
		
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{
	    super.onActivityResult(requestCode, resultCode, data); 
	    switch(requestCode) { 
	    case GALLERY_ID:
	        if(resultCode == RESULT_OK){  
	            Uri selectedImage = data.getData();
	            Intent intent = new Intent(Intent.ACTION_VIEW, selectedImage);
	            intent.putExtra("windowTitle", "My Images");
	            startActivity(intent);
	        }
	    }
	};
	
	public void onResume(){
		super.onResume();
		Button footer = (Button) (findViewById(R.id.footer_button));
        footer.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(android.R.drawable.sym_action_call), null , null);
        String contactName = PreferenceManager.getDefaultSharedPreferences(this).getString(AppConstants.PREFERENCE_EMERGENCY_NAME, "");
        if(contactName != null && contactName.length()>1){
        	footer.setText("Emergency Call to "+ contactName);
        }
        else{
        	footer.setText("Emergency Call");
        }
        
		if (((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE))
				.getPhoneType() == TelephonyManager.PHONE_TYPE_NONE) {
			footer.setVisibility(View.GONE);
		}
        footer.setOnClickListener(this);
        
	}
//	
//	@Override
//	public boolean onCreateOptionsMenu(Menu menu) {
//	    MenuInflater inflater = getMenuInflater();
//	    inflater.inflate(R.menu.activity_main, menu);
//	    return true;
//	}
//	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
			case R.id.menu_settings:
				//Toast.makeText(this, "Nothing implemented for this", Toast.LENGTH_LONG).show();
				Intent settingsIntent = new Intent(this, SettingsActivity.class);
				startActivity(settingsIntent);
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	

    private String backupDb() throws IOException {
        File sd = Environment.getExternalStorageDirectory();
        //File data = Environment.getDataDirectory();

        if (sd.canWrite()) {

            String currentDBPath = "data/data/com.sensorfriendly/databases/sensor_friendly_db";
            String backupDBPath = "/sfl.db";
            File currentDB = new File(currentDBPath);
            File backupDB = new File(sd, backupDBPath);

            if (backupDB.exists()) backupDB.delete();

            if (currentDB.exists()) {
                copy(currentDB, backupDB);
            }

           return backupDB.getAbsolutePath();
       }
        else{
            return null;
        }
    }


    private void copy(File f1, File f2) {
       /* FileChannel src = null;
        FileChannel dst = null;
        try {
            src = new FileInputStream(from).getChannel();
            dst = new FileOutputStream(to).getChannel();
            dst.transferFrom(src, 0, src.size());
        }
        finally {
            if (src != null)
                src.close();
            if (dst != null)
                dst.close();
        }*/

        try {
            InputStream in = new FileInputStream(f1);

            // For Append the file.
            // OutputStream out = new FileOutputStream(f2,true);

            // For Overwrite the file.
            OutputStream out = new FileOutputStream(f2);

            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
            System.out.println("File copied.");
        } catch (FileNotFoundException ex) {
            System.out
                    .println(ex.getMessage() + " in the specified directory.");
            System.exit(0);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

	    
}
